package com.gitee.cui.springcloud.lb;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

/**
 * 负载均衡算法的实现，轮询算法
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2022-03-05 22:35
 **/
@Component
public class MyLoadBalancer implements ILoadBalancer{

	private static final AtomicInteger count = new AtomicInteger(0);

	/**
	 * 获取访问次数
	 * @return 访问次数，第一次从1开始计算
	 */
	public int getAndIncrement() {
		int current;
		int next;
		do {
			current = count.get();
			next = current >= Integer.MAX_VALUE ? 0 : current + 1;
		} while (!count.compareAndSet(current, next));
		System.out.println("调用次数count: " + next);
		return next;
	}

	@Override
	public ServiceInstance getInstance(List<ServiceInstance> instances) {
		int size = instances.size();
		int index = getAndIncrement() % size;
		return instances.get(index);
	}
}
